Skip to main content

HIPAA-Compliant Database Wrapper API

1. Executive Summary

The HIPAA-Compliant Database Wrapper (HCDW) is a core component of the Login.Health platform, providing developers with a secure and simplified approach to handling protected health information (PHI). This document outlines the design, implementation plan, and technical specifications for creating a database abstraction layer that ensures HIPAA compliance while delivering an exceptional developer experience.

The HCDW will enable developers to focus on building innovative healthcare applications without the significant overhead of implementing complex compliance mechanisms. By handling encryption, access controls, audit logging, and other HIPAA requirements transparently, Login.Health can accelerate the development of healthcare solutions while reducing compliance risks.

2. Project Vision

2.1 Purpose

To create a database wrapper that abstracts away the complexities of HIPAA compliance while providing a developer-friendly interface for storing and retrieving healthcare data.

2.2 Key Objectives

  • Create a PostgreSQL database wrapper that enforces HIPAA compliance
  • Provide a simple, intuitive API for developers
  • Implement transparent field-level encryption for PHI
  • Ensure comprehensive audit logging
  • Support flexible access controls
  • Deliver excellent performance with minimal overhead
  • Create comprehensive documentation and developer resources

2.3 Success Metrics

MetricTargetMeasurement
Developer adoption50+ developers in year 1API usage statistics
Integration time60-80% reduction compared to custom implementationDeveloper surveys
Query performance50ms overhead compared to direct queriesPerformance benchmarks
Security compliance0 critical findings in security auditsSecurity assessment results
Developer satisfaction>85% satisfaction ratingDeveloper feedback surveys
Documentation coverage100% API coverage with examplesDocumentation completeness audit

3. Target Users

3.1 Primary User: Healthcare Application Developer

Based on the Health Tech Developer persona (Alex Chen):

  • Developing healthcare applications that need to store PHI securely
  • Has technical expertise but limited experience with healthcare compliance
  • Values developer experience and productivity
  • Seeks to minimize time spent on compliance infrastructure
  • Needs clear documentation and examples

3.2 Secondary Users

  • Security Officers: Need to verify compliance measures
  • Healthcare Administrators: Need to ensure regulatory requirements are met
  • Database Administrators: Need to manage the database infrastructure
  • Compliance Auditors: Need to verify audit trails and security controls

4. System Architecture

4.1 High-Level Architecture

4.2 Components

ComponentDescriptionResponsibility
DB Wrapper ClientClient library for application integrationProvides API to applications, handles authentication
Query ParserAnalyzes and transforms database queriesIdentifies PHI fields, validates permissions
Mutation HandlerProcesses data modification operationsValidates data, prepares for encryption
Permission CheckVerifies access rightsEnforces role-based and attribute-based access control
Audit LoggerRecords all data access eventsCreates immutable audit trail for compliance
Encryption LayerHandles data encryptionEncrypts PHI fields before storage
Decryption LayerHandles data decryptionDecrypts PHI fields after retrieval
Result ProcessorPost-processes query resultsFormats data, applies filtering

4.3 Encryption Strategy

  • Field-level encryption using AES-256-GCM
  • Key hierarchy with master keys and data encryption keys
  • Key rotation capabilities
  • Key separation for multi-tenant security

5. Feature Set

5.1 Core Features

FeatureDescriptionPriority
Field-Level EncryptionAutomatic encryption of PHI fieldsP0
Transparent DecryptionAutomatic decryption when data is accessedP0
Access ControlRole-based and attribute-based access controlP0
Audit LoggingComprehensive logging of all data accessP0
PHI ClassificationAutomatic detection and classification of PHIP0
Query APIORM-like API for data queriesP0
Key ManagementSecure key storage and rotationP0
Multi-tenancyIsolation between different applications/usersP1
Schema ManagementTools for creating and updating schemasP1
Data ValidationValidation of data formats and typesP1
Bulk OperationsOptimized handling of bulk data operationsP2
Caching LayerPerformance optimization through cachingP2
Data MigrationTools for migrating existing dataP2

5.2 API Features

FeatureDescriptionPriority
TypeScript/JavaScript SDKClient library for Node.js applicationsP0
Python SDKClient library for Python applicationsP0
Java SDKClient library for Java applicationsP1
RESTful APIHTTP API for language-agnostic accessP1
GraphQL APIGraphQL interface for flexible queriesP2
CLI ToolsCommand-line tools for administrationP2
WebSocket APIReal-time data subscriptionsP3

5.3 Developer Experience Features

FeatureDescriptionPriority
Interactive DocumentationAPI documentation with live examplesP0
Sandbox EnvironmentTest environment with synthetic dataP0
Error HandlingClear error messages and recovery pathsP0
Logging & DebuggingDeveloper-friendly logging and troubleshootingP0
Sample ApplicationsExample applications demonstrating integrationP1
Migration GuidesGuidance for migrating from other databasesP1
Schema DesignerVisual tool for designing database schemasP2
Performance AnalyticsTools for analyzing query performanceP2

6. API Design

6.1 Client SDK (TypeScript example)

// Initialize client
import { HealthDB } from "@login-health/db-wrapper";

const db = new HealthDB({
connectionString: process.env.DATABASE_URL,
applicationId: process.env.APP_ID,
applicationSecret: process.env.APP_SECRET,
encryptionKey: process.env.ENCRYPTION_KEY,
});

// Define a schema (with PHI fields marked)
const patientSchema = db.defineSchema("patient", {
id: { type: "uuid", primaryKey: true },
firstName: { type: "string", phi: true },
lastName: { type: "string", phi: true },
dateOfBirth: { type: "date", phi: true },
email: { type: "string", phi: true },
phoneNumber: { type: "string", phi: true },
address: { type: "jsonb", phi: true },
createdAt: { type: "timestamp", default: "now()" },
updatedAt: { type: "timestamp", default: "now()" },
});

// Create a patient
const patient = await db.patient.create({
data: {
firstName: "John",
lastName: "Doe",
dateOfBirth: new Date("1980-01-01"),
email: "john.doe@example.com",
phoneNumber: "555-123-4567",
address: {
street: "123 Main St",
city: "Anytown",
state: "CA",
zipCode: "12345",
},
},
});

// Query patients (PHI fields automatically decrypted)
const patients = await db.patient.findMany({
where: {
dateOfBirth: {
gte: new Date("1980-01-01"),
lt: new Date("1990-01-01"),
},
},
select: {
id: true,
firstName: true,
lastName: true,
dateOfBirth: true,
},
});

// Update a patient (PHI fields automatically encrypted)
const updatedPatient = await db.patient.update({
where: { id: patient.id },
data: {
phoneNumber: "555-987-6543",
},
});

// Access audit log
const auditEvents = await db.auditLog.findMany({
where: {
resourceType: "patient",
resourceId: patient.id,
action: "update",
},
orderBy: {
timestamp: "desc",
},
limit: 10,
});

6.2 API Operations

OperationDescriptionExample
defineSchemaDefine a database schema with PHI markingsdb.defineSchema('patient', {...})
createCreate a new recorddb.patient.create({data: {...}})
findUniqueFind a single record by unique identifierdb.patient.findUnique({where: {id: '...'}})
findManyFind multiple records matching criteriadb.patient.findMany({where: {...}})
updateUpdate an existing recorddb.patient.update({where: {...}, data: {...}})
deleteDelete a recorddb.patient.delete({where: {...}})
upsertCreate or update a recorddb.patient.upsert({where: {...}, create: {...}, update: {...}})
countCount records matching criteriadb.patient.count({where: {...}})
aggregatePerform aggregation operationsdb.patient.aggregate({_avg: {age: true}})
transactionExecute operations in a transactiondb.transaction(async (tx) => {...})

6.3 Access Control

// Define roles and permissions
db.defineRole("doctor", {
patient: {
read: true,
create: true,
update: true,
delete: false,
},
medicalRecord: {
read: true,
create: true,
update: true,
delete: false,
},
});

// Set access rules
db.setAccessRules("patient", {
read: (user, patient) => {
// Doctors can read their own patients
return user.role === "doctor" && patient.doctorId === user.id;
},
update: (user, patient) => {
// Doctors can update their own patients
return user.role === "doctor" && patient.doctorId === user.id;
},
});

// Execute query with user context
const patients = await db.patient.findMany({
where: { doctorId: currentUser.id },
context: { user: currentUser },
});

6.4 Audit Logging

Every operation is automatically logged with:

  • Timestamp
  • User identifier
  • Action type (create, read, update, delete)
  • Resource type (table/collection name)
  • Resource identifier
  • Changed fields (for updates)
  • Access context
  • Client information

Audit logs are immutable and stored in a separate table with strict access controls.

7. Development Roadmap

8. Project Epics and User Stories

8.1 Epics

Epic IDTitleDescriptionPriority
E1Foundation ArchitectureEstablish the core architecture for the HIPAA DB WrapperP0
E2Encryption SystemImplement the field-level encryption systemP0
E3Access ControlDevelop the access control frameworkP0
E4Audit LoggingImplement comprehensive audit loggingP0
E5Core API DevelopmentBuild the main query and manipulation APIP0
E6SDK DevelopmentCreate client SDKs for multiple languagesP0
E7Developer ExperienceEnhance developer experience with documentation and toolsP1
E8Testing & SecurityComprehensive testing and security hardeningP0
E9Performance OptimizationOptimize performance for production useP1
E10Advanced FeaturesImplement additional features for enhanced functionalityP2

8.2 User Stories by Epic

E1: Foundation Architecture

IDUser StoryAcceptance CriteriaPoints
US1.1As a developer, I want to connect to a PostgreSQL database through the wrapper• Connection established with proper credentials
• Connection pooling implemented
• Error handling for connection issues
5
US1.2As a developer, I want to define database schemas with PHI indicators• Schema definition API created
• PHI field marking supported
• Schema validation implemented
8
US1.3As a system architect, I need a multi-layered security design• Security architecture documented
• Implementation plan created
• Security review completed
5
US1.4As a developer, I want basic CRUD operations working through the wrapper• Create operation implemented
• Read operation implemented
• Update operation implemented
• Delete operation implemented
13
US1.5As a developer, I want to initialize the wrapper with configuration options• Configuration schema defined
• Validation of configuration
• Sensible defaults provided
3

E2: Encryption System

IDUser StoryAcceptance CriteriaPoints
US2.1As a security officer, I want PHI to be encrypted at rest• AES-256-GCM encryption implemented
• Field-level encryption working
• Encryption performance benchmarked
13
US2.2As a developer, I want encryption to be transparent in queries• Automatic encryption on write
• Automatic decryption on read
• Proper error handling for encryption failures
8
US2.3As a security officer, I want a key hierarchy for enhanced security• Master key implementation
• Data encryption key generation
• Key wrapping implementation
13
US2.4As a system admin, I want to rotate encryption keys periodically• Key rotation API designed
• Data re-encryption process
• Minimal downtime during rotation
8
US2.5As a developer, I want to search on encrypted fields• Searchable encryption implementation
• Query translation for encrypted fields
• Performance testing for searches
13

E3: Access Control

IDUser StoryAcceptance CriteriaPoints
US3.1As a security officer, I want role-based access control• Role definition API
• Permission assignment to roles
• Role validation during queries
8
US3.2As a developer, I want to set access rules for different tables• Table-level access rules
• Rule evaluation during queries
• Documentation on setting rules
5
US3.3As a security officer, I want attribute-based access control• ABAC implementation
• Context-aware permission checks
• Combining RBAC and ABAC
13
US3.4As a developer, I want to include user context in queries• Context parameter in queries
• Context validation
• Context utilization in access rules
5
US3.5As a security officer, I want to enforce purpose limitations• Purpose specification in queries
• Purpose validation
• Purpose enforcement
8

E4: Audit Logging

IDUser StoryAcceptance CriteriaPoints
US4.1As a compliance officer, I want all data access logged• Comprehensive audit logging
• All CRUD operations logged
• User identification in logs
8
US4.2As a security officer, I want immutable audit logs• Immutable storage design
• Tamper-evident logging
• Log verification mechanism
8
US4.3As a compliance officer, I want to query audit logs• Audit log query API
• Filtering capabilities
• Pagination for large logs
5
US4.4As a developer, I want audit logging to have minimal performance impact• Performance benchmarking
• Asynchronous logging
• Log batching for performance
5
US4.5As a compliance officer, I want detailed information about data changes• Before/after values recorded
• Changed fields identified
• Change reason capture
5

E5: Core API Development

IDUser StoryAcceptance CriteriaPoints
US5.1As a developer, I want a familiar query API similar to modern ORMs• Intuitive query API
• Similar patterns to Prisma/Sequelize
• Documentation with examples
13
US5.2As a developer, I want to perform complex queries with filtering• Complex where clauses
• Nested queries
• Query optimization
8
US5.3As a developer, I want to perform transactions across multiple operations• Transaction API
• Rollback capability
• Error handling in transactions
8
US5.4As a developer, I want to use common database operations (join, group, sort)• Join operations
• Grouping and aggregation
• Sorting and pagination
13
US5.5As a developer, I want clear error messages for failed operations• Detailed error messages
• Error categorization
• Suggestions for resolution
5

E6: SDK Development

IDUser StoryAcceptance CriteriaPoints
US6.1As a TypeScript developer, I want a type-safe SDK• TypeScript SDK
• Type definitions
• Intellisense support
13
US6.2As a Python developer, I want a Python SDK• Python SDK
• Python idioms followed
• Package published to PyPI
13
US6.3As a developer, I want consistent API patterns across languages• Consistent naming
• Similar method signatures
• Shared documentation patterns
5
US6.4As a developer, I want SDK versioning that follows semver• Semantic versioning
• Changelog maintenance
• Backward compatibility policy
3
US6.5As a developer, I want SDK examples for common operations• Example code for CRUD
• Examples for complex queries
• Examples for transactions
5

E7: Developer Experience

IDUser StoryAcceptance CriteriaPoints
US7.1As a developer, I want interactive API documentation• API documentation site
• Interactive examples
• Try-it-now functionality
8
US7.2As a developer, I want a sandbox environment for testing• Sandbox provision process
• Synthetic test data
• Reset capability
8
US7.3As a developer, I want step-by-step integration guides• Getting started guide
• Integration patterns
• Troubleshooting guide
5
US7.4As a developer, I want to validate my implementation• Compliance checklist
• Validation tools
• Self-assessment guide
5
US7.5As a developer, I want example applications demonstrating the wrapper• Example applications
• Best practices demonstrated
• Source code available
8

E8: Testing & Security

IDUser StoryAcceptance CriteriaPoints
US8.1As a security officer, I want the wrapper to pass security testing• OWASP testing
• Penetration testing
• Vulnerability assessment
13
US8.2As a quality engineer, I want comprehensive test coverage• 90%+ code coverage
• Unit tests for all components
• Integration tests for workflows
13
US8.3As a developer, I want the wrapper to handle edge cases• Error handling
• Boundary testing
• Fault injection testing
8
US8.4As a security officer, I want security scanning in the CI pipeline• Automated security scanning
• Dependency vulnerability checks
• Secret scanning
5
US8.5As a compliance officer, I want HIPAA requirement validation• Technical safeguards validated
• Documentation for compliance
• Gap analysis
8

E9: Performance Optimization

IDUser StoryAcceptance CriteriaPoints
US9.1As a developer, I want minimal query overhead• 50ms overhead per query
• Performance testing methodology
• Baseline comparisons
8
US9.2As a developer, I want efficient handling of large datasets• Pagination implementation
• Streaming large results
• Memory optimization
8
US9.3As a systems engineer, I want connection pooling for throughput• Connection pool implementation
• Pool configuration options
• Pool metrics
5
US9.4As a developer, I want query optimization suggestions• Query analysis
• Performance suggestions
• Index recommendations
8
US9.5As a developer, I want caching options for repeated queries• Query result caching
• Cache invalidation
• Cache configuration
8

E10: Advanced Features

IDUser StoryAcceptance CriteriaPoints
US10.1As a developer, I want data versioning capabilities• Data versioning API
• Historical query support
• Version comparison
13
US10.2As a data scientist, I want anonymized data export• De-identification process
• Export functionality
• Format options
8
US10.3As a developer, I want schema migration tools• Schema migration API
• Migration scripts
• Rollback capability
13
US10.4As a developer, I want real-time data subscriptions• WebSocket API
• Subscription management
• Event filtering
13
US10.5As a developer, I want to set data retention policies• Retention policy API
• Automated data archiving
• Compliance documentation
8

9. Implementation Considerations

9.1 Technology Stack

ComponentTechnologyRationale
DatabasePostgreSQLStrong security features, enterprise-grade, excellent JSON support
Backend LanguageTypeScript/Node.jsStrong typing, async performance, large ecosystem
EncryptionAES-256-GCMIndustry standard, authenticated encryption
Key ManagementAWS KMS / HashiCorp VaultEnterprise-grade key security
API DesignREST + TypeScriptUniversal compatibility, strong typing
DocumentationOpenAPI + DocusaurusIndustry standard, interactive capabilities
TestingJest, SuperTestComprehensive testing framework
CI/CDGitHub ActionsModern CI/CD, integrates with development workflow

9.2 Performance Considerations

  • Query Optimization: Minimize overhead for PHI detection and encryption
  • Caching Strategy: Cache frequently accessed non-PHI data
  • Indexing Strategy: Special considerations for encrypted fields
  • Connection Pooling: Optimize database connections
  • Batch Processing: Efficient handling of bulk operations

9.3 Security Considerations

  • Key Management: Secure storage and rotation of encryption keys
  • Authentication: Integration with Login.Health authentication system
  • Authorization: Fine-grained access control
  • Audit Trail: Comprehensive, immutable logging
  • Vulnerability Management: Regular security assessments

9.4 Compliance Considerations

  • HIPAA Technical Safeguards: Encryption, access controls, audit logs
  • Documentation: Comprehensive documentation for compliance verification
  • Risk Assessment: Regular security and compliance assessments
  • Breach Notification: Procedures for identifying and reporting breaches
  • BAA Support: Business Associate Agreement considerations

10. Testing Strategy

10.1 Testing Levels

Test LevelDescriptionToolsCoverage Target
Unit TestingTesting individual componentsJest90% code coverage
Integration TestingTesting component interactionsJest + SuperTestKey workflows
Security TestingVulnerability assessmentOWASP ZAP, SnykAll endpoints
Performance TestingMeasuring performancek6, autocannonKey operations
Compliance TestingValidating HIPAA requirementsCustom checklistAll requirements

10.2 Test Scenarios

  1. Encryption/Decryption

    • PHI fields are properly encrypted
    • Non-PHI fields remain unencrypted
    • Decryption works correctly
    • Invalid encryption keys are rejected
  2. Access Control

    • Users can only access authorized data
    • Role-based permissions work as expected
    • Attribute-based rules are enforced
    • Unauthorized access attempts are blocked and logged
  3. Audit Logging

    • All operations are logged
    • Logs contain all required information
    • Logs are immutable
    • Log queries work correctly
  4. API Functionality

    • CRUD operations work as expected
    • Complex queries function correctly
    • Transactions maintain data integrity
    • Error handling works correctly
  5. Performance

    • Query overhead is within acceptable limits
    • Large dataset handling is efficient
    • Connection pooling works correctly
    • System handles concurrent operations

11. Documentation Plan

11.1 Documentation Components

ComponentPurposeFormatAudience
API ReferenceDetailed API documentationOpenAPI + MarkdownDevelopers
Getting Started GuideQuick start instructionsMarkdown + ExamplesNew developers
Integration PatternsCommon integration approachesMarkdown + DiagramsArchitects
Security OverviewSecurity architectureMarkdown + DiagramsSecurity officers
Compliance GuideHIPAA compliance detailsMarkdown + ChecklistCompliance officers
ExamplesExample code for common tasksCode repositoriesDevelopers
TutorialsStep-by-step instructionsInteractive guidesNew developers
FAQCommon questions and answersMarkdownAll users

11.2 Documentation Approach

  • Interactive Documentation: Live API examples
  • Code Examples: Multiple languages
  • Visual Diagrams: Architecture and flows
  • Video Tutorials: Key concepts and implementations
  • Regular Updates: Documentation as a living resource

12. Rollout Plan

12.1 Phase 1: Alpha (Week 1-6)

  • Internal development
  • Architecture implementation
  • Basic functionality
  • Unit testing

12.2 Phase 2: Beta (Week 7-14)

  • Internal developer preview
  • Core API implementation
  • TypeScript SDK
  • Initial documentation
  • Security review

12.3 Phase 3: Developer Preview (Week 15-18)

  • Limited external developer access
  • Complete core functionality
  • Python SDK
  • Comprehensive documentation
  • Performance optimization

12.4 Phase 4: General Availability (Week 19-24)

  • Full production launch
  • All planned SDKs
  • Complete documentation
  • Support resources
  • Marketing materials

13. Success Criteria and KPIs

13.1 Initial Launch Success Criteria

  • HIPAA compliance verified through security assessment
  • All P0 features implemented and tested
  • Documentation complete for core functionality
  • Performance benchmarks meet targets
  • Initial developer feedback positive

13.2 Ongoing KPIs

KPITargetMeasurement
Developer Adoption50+ active developers in year 1API usage metrics
Query Performance50ms average overheadPerformance monitoring
Documentation Satisfaction>85% satisfactionDeveloper surveys
Integration Time1 week averageDeveloper feedback
Support Tickets10 per weekSupport system metrics
Security Incidents0Security monitoring

14. Team Structure

RoleResponsibilitiesSkills Required
Technical LeadArchitecture, technical decisionsDatabase security, HIPAA, API design
Backend Developer (2)Core implementation, SDKsNode.js, PostgreSQL, encryption
Security EngineerSecurity implementation, reviewEncryption, security architecture
QA EngineerTesting strategy, implementationAutomated testing, security testing
Documentation SpecialistDeveloper docs, examplesTechnical writing, API documentation
Product ManagerRequirements, roadmap, prioritizationHealthcare experience, developer empathy
DevOps EngineerCI/CD, infrastructureAWS, PostgreSQL administration, security

15. Risks and Mitigations

RiskImpactLikelihoodMitigation Strategy
Performance overhead too highHighMediumEarly performance testing, optimization spikes, architectural adjustments
Encryption complexity impacts usabilityHighMediumExtensive developer testing, intuitive API design, comprehensive examples
Security vulnerabilitiesCriticalLowRegular security reviews, penetration testing, external audit
Compliance gapsCriticalLowHIPAA expert consultation, compliance checklist, documentation
Integration challenges with existing systemsMediumHighFlexible adapter patterns, comprehensive documentation, support resources
Key management complexityHighMediumWell-designed key rotation, backup procedures, documentation
Developer adoption barriersHighMediumDeveloper experience focus, excellent documentation, sample applications
Database schema evolution challengesMediumMediumSchema migration tools, versioning support, backward compatibility

16. Dependencies

DependencyTypeImpactManagement Strategy
PostgreSQLTechnologyCore databaseIsolation through abstraction layer, version compatibility testing
Authentication SystemInternalUser context for permissionsWell-defined interfaces, mock during development
Encryption LibrariesExternalData securityEvaluated libraries, possible fallback options
Key Management SystemExternalKey securityAbstraction layer, support for multiple providers
Cloud InfrastructureExternalHosting environmentInfrastructure as code, environment parity
Regulatory RequirementsExternalComplianceRegular monitoring, compliance expertise

17. Integration Points

17.1 Authentication System

Integration with Login.Health's authentication system to:

  • Validate user identity
  • Obtain user roles and attributes
  • Enforce session management
  • Support single sign-on

17.2 Encrypted Datastore

Integration with the core datastore to:

  • Manage encryption keys
  • Implement field-level encryption
  • Maintain audit logs
  • Handle data migrations

17.3 Developer Platform

Integration with the Login.Health developer platform to:

  • Register applications
  • Manage API credentials
  • Monitor usage metrics
  • Access documentation

17.4 Healthcare Provider Systems

Integration capabilities for healthcare providers to:

  • Import existing data
  • Normalize data formats
  • Map to standard schemas
  • Maintain data integrity

18. Glossary

TermDefinition
PHIProtected Health Information - individually identifiable health information
HIPAAHealth Insurance Portability and Accountability Act
BAABusiness Associate Agreement
Field-Level EncryptionEncrypting individual fields rather than entire database
RBACRole-Based Access Control
ABACAttribute-Based Access Control
AES-256-GCMAdvanced Encryption Standard with 256-bit key size using Galois/Counter Mode
DEKData Encryption Key - key used to encrypt actual data
KEKKey Encryption Key - key used to encrypt other keys
SDKSoftware Development Kit

19. References

  1. HIPAA Security Rule - 45 CFR Part 160 and Subparts A and C of Part 164
  2. NIST Special Publication 800-66 - Implementing the HIPAA Security Rule
  3. OWASP Security Standards for Healthcare Applications
  4. PostgreSQL Security Best Practices
  5. Field-Level Encryption Implementation Patterns
  6. Key Management Best Practices (NIST SP 800-57)
  7. Login.Health System Architecture Documentation
  8. PostgreSQL JSON/JSONB Documentation

20. Appendices

Appendix A: Detailed Encryption Implementation

// Key hierarchy implementation
class KeyHierarchy {
// Master key - managed by key management service
private masterKey: Buffer;

// Data encryption keys - encrypted with master key
private dataEncryptionKeys: Map<string, EncryptedKey>;

constructor(masterKeyIdentifier: string) {
// Retrieve master key from secure storage
this.masterKey = KeyManagementService.getKey(masterKeyIdentifier);
this.dataEncryptionKeys = new Map();
}

// Generate a new data encryption key for a tenant
public generateDataEncryptionKey(tenantId: string): string {
// Generate random key
const dek = crypto.randomBytes(32);

// Encrypt with master key
const encryptedDek = this.encryptWithMasterKey(dek);

// Store encrypted DEK
const keyId = uuid.v4();
this.dataEncryptionKeys.set(keyId, {
tenantId,
encryptedKey: encryptedDek,
createdAt: new Date(),
});

return keyId;
}

// Get DEK for encryption/decryption
public getDataEncryptionKey(keyId: string): Buffer {
const encryptedKey = this.dataEncryptionKeys.get(keyId);
if (!encryptedKey) {
throw new Error(`Key not found: ${keyId}`);
}

// Decrypt with master key
return this.decryptWithMasterKey(encryptedKey.encryptedKey);
}

// Encrypt data with a specific DEK
public encryptField(keyId: string, data: string): EncryptedData {
const dek = this.getDataEncryptionKey(keyId);

// Generate initialization vector
const iv = crypto.randomBytes(16);

// Create cipher
const cipher = crypto.createCipheriv("aes-256-gcm", dek, iv);

// Encrypt
let encrypted = cipher.update(data, "utf8", "base64");
encrypted += cipher.final("base64");

// Get auth tag
const authTag = cipher.getAuthTag();

return {
keyId,
iv: iv.toString("base64"),
authTag: authTag.toString("base64"),
data: encrypted,
};
}

// Decrypt data with a specific DEK
public decryptField(encryptedData: EncryptedData): string {
const dek = this.getDataEncryptionKey(encryptedData.keyId);

// Recreate decipher
const decipher = crypto.createDecipheriv(
"aes-256-gcm",
dek,
Buffer.from(encryptedData.iv, "base64")
);

// Set auth tag
decipher.setAuthTag(Buffer.from(encryptedData.authTag, "base64"));

// Decrypt
let decrypted = decipher.update(encryptedData.data, "base64", "utf8");
decrypted += decipher.final("utf8");

return decrypted;
}

// Helper methods for master key operations
private encryptWithMasterKey(data: Buffer): Buffer {
// Implementation using master key
}

private decryptWithMasterKey(data: Buffer): Buffer {
// Implementation using master key
}
}

Appendix B: Example Schema Definition

// Example schema definition with PHI marking
const patientSchema = db.defineSchema("patient", {
id: {
type: "uuid",
primaryKey: true,
defaultValue: "uuid_generate_v4()",
},
firstName: {
type: "string",
maxLength: 100,
phi: true,
},
lastName: {
type: "string",
maxLength: 100,
phi: true,
},
dateOfBirth: {
type: "date",
phi: true,
},
gender: {
type: "string",
enum: ["male", "female", "other", "prefer_not_to_say"],
phi: true,
},
email: {
type: "string",
format: "email",
phi: true,
},
phoneNumber: {
type: "string",
phi: true,
},
address: {
type: "jsonb",
phi: true,
properties: {
street: { type: "string" },
city: { type: "string" },
state: { type: "string" },
zipCode: { type: "string" },
country: { type: "string" },
},
},
medicalRecordNumber: {
type: "string",
unique: true,
phi: true,
},
insuranceProvider: {
type: "string",
phi: false,
},
insuranceMemberId: {
type: "string",
phi: true,
},
primaryCareProviderId: {
type: "uuid",
phi: false,
references: {
table: "provider",
column: "id",
},
},
allergies: {
type: "jsonb",
phi: true,
array: true,
},
medications: {
type: "jsonb",
phi: true,
array: true,
},
createdAt: {
type: "timestamp",
defaultValue: "now()",
phi: false,
},
updatedAt: {
type: "timestamp",
defaultValue: "now()",
phi: false,
},
});

// Define access rules
db.setAccessRules("patient", {
read: (user, patient) => {
return (
// Doctors can read their patients
(user.role === "doctor" && patient.primaryCareProviderId === user.id) ||
// Nurses can read patients in their department
(user.role === "nurse" && user.departmentId === patient.departmentId) ||
// Admins can read all patients
user.role === "admin" ||
// Patients can read their own records
(user.role === "patient" && patient.id === user.id) ||
// Surrogates can read their dependents' records
isSurrogateFor(user.id, patient.id)
);
},
update: (user, patient) => {
return (
// Doctors can update their patients
(user.role === "doctor" && patient.primaryCareProviderId === user.id) ||
// Admins can update all patients
user.role === "admin"
);
},
delete: (user, patient) => {
// Only admins can delete patient records
return user.role === "admin";
},
});

Appendix C: Query Examples

// Find patients with a specific condition
const diabeticPatients = await db.patient.findMany({
where: {
conditions: {
arrayContains: {
code: "E11", // Type 2 Diabetes ICD-10 code
},
},
},
select: {
id: true,
firstName: true,
lastName: true,
dateOfBirth: true,
medications: true,
},
context: {
user: currentUser,
purpose: "treatment",
},
});

// Update a patient's contact information
const updatedPatient = await db.patient.update({
where: {
id: patientId,
},
data: {
phoneNumber: newPhoneNumber,
address: {
street: newStreet,
city: newCity,
state: newState,
zipCode: newZipCode,
},
},
context: {
user: currentUser,
purpose: "administrative",
},
});

// Transaction example
const result = await db.transaction(
async (tx) => {
// Create a new patient
const patient = await tx.patient.create({
data: {
firstName: "Jane",
lastName: "Doe",
dateOfBirth: new Date("1980-05-15"),
gender: "female",
email: "jane.doe@example.com",
},
});

// Create initial medical record
const medicalRecord = await tx.medicalRecord.create({
data: {
patientId: patient.id,
providerId: currentUser.id,
visitDate: new Date(),
diagnosis: "Annual checkup",
notes: "Patient appears healthy",
},
});

return { patient, medicalRecord };
},
{
context: {
user: currentUser,
purpose: "treatment",
},
}
);

// Query with complex filtering
const highRiskPatients = await db.patient.findMany({
where: {
OR: [
{
// Elderly patients with heart conditions
dateOfBirth: {
lt: new Date(new Date().setFullYear(new Date().getFullYear() - 65)),
},
conditions: {
arrayContains: {
code: {
in: ["I21", "I25", "I50"], // Heart conditions
},
},
},
},
{
// Diabetic patients with kidney issues
conditions: {
arrayContains: [
{ code: "E11" }, // Diabetes
{ code: "N18" }, // Chronic kidney disease
],
},
},
],
},
include: {
medications: true,
recentLabResults: {
orderBy: { date: "desc" },
take: 5,
},
},
context: {
user: currentUser,
purpose: "population_health",
},
});